<?php

namespace App\Http\Middleware;

use App\Models\SysMenu;
use App\Models\SysOperLog;
use Closure;
use Illuminate\Http\Request;

class SysRequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $request_route_name = $request->route()->getName();
        $path = $request->path();

        $perm = str_replace('.', ':', $request_route_name);
        $menu_name = SysMenu::where('perms',$perm)->value('menu_name');

        $params = $request->all();
        $user_id = 0;
        if(auth()->id()){
            $user_id = auth()->id();
        }
        //只记录POST
        if($request->isMethod('POST')){
            if(isset($params['password'])){
                $params['password'] = '******';
            }
            if(isset($params['new_password'])){
                $params['new_password'] = '******';
            }
            if(isset($params['old_password'])){
                $params['old_password'] = '******';
            }
            SysOperLog::create([
                'request_method' => $request->method(),
                'oper_url' => $path,
                'oper_ip' => $request->ip(),
                'oper_name' => $menu_name,
                'oper_param' => is_array($params) ? json_encode($params) : $params,
            ]);
        }

        return $next($request);
    }
}
